var datas;
var mainDiv;
var elements;
var col,row;
var columnIndex; //first column index in data
var vCols = 5; //(4+1); 4 is default visible columns. 1 is either combox box column or delete column
function makeGrid(e,data,visibleColumns)
{
	mainDiv=e;
	datas = data;
	columnIndex=0;
	if (visibleColumns) vCols = (visibleColumns + 1);
	elements= new Array();
	
	elements.push("<div class='contentTitleGrey'>A380 Flight Leg Availability</div><table class='datatable' cellpadding='0' cellspacing='0'>");	
	addHeader();	
	$(datas.row).each(function(e){ elements.push(getBulkRow(this).join('')); });	
	elements.push("</table><div class='footer'><div class='footerIn'><input type='button' value='Add row' class='btnGreyB' onclick='addRow()'/><input type='button' value='Export' class='btnGrey'/><input type='button' value='Save' class='btnGrey' onclick='saveData()'/></div></div>");	
	$(e).html(elements.join(''));	
	placeDatePicker();
	oddeven();

}

function addHeader()
{
    elements.push("<tr class='headerRow'><th id='previousDataTH' class='databorderTl'><input type='button'  onclick='getPreviousData()' value='<'/></th>");
	$(datas.data[0].data).each(function(e){		
		elements.push("<th>"+this.date+"</th>");		
	})
	elements.push("<th id='nextDataTH' class='databorderTr' ><input type='button' onclick='getNextData(this)' value='&gt;'/></th></tr>");
}


function getBulkRow(row)
{
	var retArray = new Array();
	var selectArray = new Array();
    selectArray.push("<select  ONCHANGE=\"onDAIMChanged(this);\">");
	
    $(datas.data).each(function(e) {
    	var selected= (( row.defaultDAIM == this.D_AIM) ? " selected='selected' " : "");
        selectArray.push("<option " + selected + " value='" + row.day_view + this.D_AIM  + "'>D-AIM" + this.D_AIM + "</option>");	
    });
    selectArray.push("</select>");	
    
    $(datas.data).each(function(e) {
    	
    	
    	retArray.push(getRow(this,row,selectArray,e));
    	
			
    });
    
	
	
	
	
	return retArray;
	
}

function getRow(rowData,row,selectArray,e,classname) {


var retVal = new String();
    retVal = "<tr "+((e==0)?"tag='mainRow'":"")+" class='dataRow row" + row.day_view + "' id='" + row.day_view + rowData.D_AIM + "' " + ((!row.visible  || rowData.D_AIM != row.defaultDAIM) ? ' style="display:none"' : ' ') + "  ><td tag='row" + row.day_view + "' id='comboTD" + row.day_view + rowData.D_AIM + "' class='databorderTl'>";	
	var cellArray=new Array();
	$(rowData.data).each(function(e){		
		cellArray.push(getCell(this));	
	});	
	retVal = retVal.concat(selectArray.join(''));
	retVal = retVal.concat(cellArray.join(''));
	retVal = retVal.concat("<td tag='row" + row.day_view + "' id='deleteTD" + row.day_view + rowData.D_AIM + "' class='databorderTr'><a href='#' onclick='deleteRow(this)' class='minus'></a></td></tr>");

return retVal;
}

function getCell(cellData)
{
    var retVal = new String();
	retVal = "<td><div class='datatd'><div class='datatdin'>"
	if (cellData.icons) {
	    retVal = retVal.concat(getIcons(cellData.icons));
	}
	retVal=retVal.concat("<span class='dataname'>"+cellData.name+"</span><br>Avail: "+cellData.avail+"<br>Resets: "+cellData.resets+" <br> Impacts: "+cellData.impacts+" </div> </div></td>");
	return retVal;
}

function getIcons(iconData) {
    var retVal=new String();
    $(iconData).each(function(e){
        retVal = retVal.concat("<a href='#'  class='"+this.classname+"' onclick='"+this.action+";'></a>");
    });
    return retVal;    
}

function onDAIMChanged(e) {
    $(mainDiv).find('tr.' + $(e).parents('td').attr('tag')).hide();    
    $(mainDiv).find('tr#' + e.options[e.selectedIndex].value).show().find('select').val(e.options[e.selectedIndex].value);
}

function deleteRow(e)
{

//$(e).parent().siblings('.databorderTl').find('select option[selected]').removeAttr('selected');//change selected value to default of combobox
	var parentClassname=$(e).parents('td').attr('tag');
	var trs=$(mainDiv).find('tr.' + parentClassname).hide();	
	$(trs).parent().append(trs);
	oddeven();
	
}

function getPreviousData()
{
	var d =new Date($('#dpicker').datepicker('getDate'));
	d.setDate(d.getDate()-1);
	
	getPrevDataFromServer(d)
}

function getNextData(e)
{
    var d = new Date($(e).parent('th').prev().text().split('-').join('/')); // hack for ubuntu firefox and IE, both doesnot support dateformat with hypen (-)
	d.setDate(d.getDate()+1);
	getNextDataFromServer(d);
}

function placeDatePicker() {
    if($('#dpicker').length>0) // on initial time, dpicker is not exists. 
    {
    	var tempDate = $('#dpicker').datepicker('getDate');
    	var dateformat = $.datepicker.formatDate('yy-mm-dd', tempDate);
    	$('#dpicker').parent('th').html(dateformat);
    	$('#dpicker').remove();
    }
    var newdate= new Date($(".headerRow th:nth-child(" + (columnIndex + 2) + ")").html().split('-').join('/'));// hack for ubuntu firefox and IE, both doesnot support dateformat with hypen (-)

    $(".headerRow th:nth-child(" + (columnIndex + 2) + ")").html('<input id="dpicker" type="text" />'); //here 2 is 2nd column where datepicker will be placed
    $('#dpicker').datepicker({
		onSelect: function(dateText, inst) {
			//datepicker date is change and need to ask data to server.
			
			makeGrid(mainDiv,dummyDataAgain,vCols);
		}
	});
    $("#dpicker").datepicker("setDate", newdate);
}

//get one day earlier data , d is date for requesting on server
function getPrevDataFromServer(d)
{
	if(columnIndex==0)
	{
	    var dummy = dummyData; //here we have get data from server , formated on data.js
	    //if data recieve from server the do below codes
	    $('#myGrid table tr td:nth-child(' + (vCols-1) + '),#myGrid table tr th:nth-child(' + (vCols-1) + ')').nextAll().not('.databorderTr').hide();
    	cacheData(dummy,0);//caching data and inserting at 0 index column
    	
    	$(datas.row).each(function(e){
    		var bulkRowData = this;
    		$(dummy.data).each(function(f){
    			var rowData=this;
    			$(this.data).each(function(g)
    			{
    				$('#comboTD' + bulkRowData.day_view + rowData.D_AIM).after(getCell(this));
    			});
    		});    	
    	});    	
    	$('#previousDataTH').after('<th>' + $.datepicker.formatDate('yy-mm-dd', d) + '</th>');
    }
	else
	{
		columnIndex-=1;
		$('.headerRow th:nth-child('+(columnIndex+2)+')').show();
		$('.dataRow td:nth-child('+(columnIndex+2)+')').show();
		
    	$('#myGrid table tr td:nth-child('+(columnIndex+vCols)+'),#myGrid table tr th:nth-child('+(columnIndex+vCols)+')').nextAll().not('.databorderTr').hide();
 }
 placeDatePicker();
}

//get one day Later data , d is date for requesting on server
function getNextDataFromServer(d)
{
    columnIndex += 1;
    var noOfHiddenColumn=$('.headerRow th').length  - columnIndex - vCols;
    if(noOfHiddenColumn>0)
    {
        $('.headerRow th:nth-child('+(columnIndex+vCols)+')').show();
        $('.dataRow td:nth-child(' + (columnIndex + vCols) + ')').show();
        $('#myGrid table tr td:nth-child(' + (columnIndex + 2) + '),#myGrid table tr th:nth-child(' + (columnIndex + 2) + ')').prevAll().not('.databorderTl').hide();
    }
    else
    {
        $('#myGrid table tr td:nth-child('+(columnIndex+1)+'),#myGrid table tr th:nth-child('+(columnIndex+1)+')').hide();
	    var dummy = dummyData;//here we have get data from server , formated on data.js
	    cacheData(dummy)
    	
    	$(datas.row).each(function(e){
    		var bulkRowData = this;
    		$(dummy.data).each(function(f){
    			var rowData=this;
    			$(this.data).each(function(g)
    			{
    				$('#deleteTD' + bulkRowData.day_view + rowData.D_AIM).before(getCell(this));
    			});
    		});    	
    	}); 
	    $('#nextDataTH').before('<th>'+$.datepicker.formatDate('yy-mm-dd', d)+'</th>');
    
    }
    placeDatePicker();
}


function addRow()
{
var temp;
	$('.dataRow[tag=mainRow]:hidden').each(
	
		function(e){
			var cls = $(this).attr('class').split(' ')[1];
			var notHidden = $('.'+cls+':not(:hidden)');
			if(temp)return;
			if(!notHidden.length)
			{
				temp= $(this).show();
				return;
			}
		});	
		oddeven();
}

function oddeven()
{
	$(".datatable tr:not('.headerRow')").not(':hidden').each(function(e){
			if(e%2!=0)
			$(this).addClass('even');
			else
			$(this).removeClass('even');
		});
}

//data: data from server, index: where to insert.
function cacheData(data,index)
{	
	for(var i=0 ; i<data.data.length;i++)
	{
		
		if(index>=0)
		    datas.data[i].data.splice(index,0,data.data[i].data[0]);//storing data at first index			
		else
		    datas.data[i].data.push(data.data[i].data[0]);//storing data at last column index
			
	}
}




function saveData()
{		
	
	var datatosave= new Object();
	datatosave.colIndex=columnIndex;
	datatosave.data=datas;
	str= JSON.stringify(datatosave);	
	var output="";
	var strs=new Array();	
	var index = 0;
	var maxLength=1000;
    while(true) {
		var chunck = str.substring(index, (maxLength+index));
		strs.push(chunck);
		$.cookie('systemOverview' + index, chunck);
		if (index>= str.length) break;
        index += maxLength;		
    }	
	
}


